<?php
namespace app\api\controller;

use app\api\controller;
use wxapp\aes\WXBizDataCrypt;
use think\Validate;
use think\Db;


class Login extends Base
{   

   public function login()
    {
        $validate = new Validate(['code'=> 'require']);
        $validate->message(['code.require' => '缺少参数code!']);

        $data = $this->request->param();

        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        
        $code          = $data['code'];
       
        $wxapp_config_info    = get_wxapp_config();

        $response = curl_get("https://api.weixin.qq.com/sns/jscode2session?appid={$wxapp_config_info['appid']}&secret={$wxapp_config_info['secret']}&js_code=$code&grant_type=authorization_code");

        $response = json_decode($response,true);

        if (!empty($response['errcode'])) {
            $this->error('操作失败!');
        }

        $openid     = $response['openid'];
        $session_key = $response['session_key'];

        $user_info = Db::name("user")->where('openid',$openid)->find();

        $token          = md5(uniqid()) . md5(uniqid());
        $current_time   = time();

        if($user_info){
            $user_data = [
               'session_key'     => $session_key,
               'token'           => $token,
               'last_visit_time' => $current_time,
               'visit_times'     => ['exp','visit_times+1'],
            ];

            Db::name('user')->where('openid',$openid)->update($user_data);
        }else{
            Db::name("user")->insert([
                'token'           => $token,
                'session_key'     => $session_key,
                'openid'          => $openid,
                'last_visit_time' => $current_time,
                'create_time'     => $current_time,
                'device_type'     => 'wxapp',
            ]);
        }

        $user = Db::name('user')->where('openid', $openid)->field('id,mobile,money,deposit')->find();

        //判断用户是否在使用球杆
        $cue_number = Db::name('cue_status')->where('user_id',$user['id'])->value('cue_number');
        $cue_number = $cue_number ? $cue_number : 0; 
        

        $this->success("登录成功!", ['token' => $token, 'user' => $user,'cue_number' => $cue_number]);

    
    }

    public function addWxappUserInfo(){
        $validate = new Validate([
            'encrypted_data' => 'require',
            'iv'             => 'require',
            'raw_data'       => 'require',
            'signature'      => 'require',
        ]);

        $validate->message([
            'encrypted_data.require' => '缺少参数encrypted_data!',
            'iv.require'             => '缺少参数iv!',
            'raw_data.require'       => '缺少参数raw_data!',
            'signature.require'      => '缺少参数signature!',
        ]);

        $data = $this->request->param();

        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        $user_info = $this->user;
        $wxapp_config_info  = get_wxapp_config();
       
        $pc      = new WXBizDataCrypt($wxapp_config_info['appid'],$user_info['session_key']);
       
        $errCode = $pc->decryptData($data['encrypted_data'], $data['iv'], $wxUserData);
       
        if ($errCode != 0) {
            $this->error('操作失败!');
        }
        
        unset($wxUserData['watermark']);
        
       
        
        Db::name('user')->where('id',$this->userId)->update([
            'nick_name'   => $wxUserData['nickName'],
            'avatar_url'  => $wxUserData['avatarUrl'],
            'more'        => json_encode($wxUserData)
            ]);
        $this->success("添加成功");
    }

}